import React, { useState, useEffect } from 'react'
import { Card, Button, Space, Modal, message, Tabs, Descriptions, Tag, Avatar, Row, Col, Select, Form as AntForm } from 'antd'
import { PlusOutlined, EditOutlined, DeleteOutlined, UserOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import DataTable from '../../../components/common/DataTable'
import Form from '../../../components/common/Form'

// 引入API
import { listEmployees, createEmployee, getEmployee, updateEmployee, deleteEmployee } from '../../../api/employee'
import { getDepartments } from '../../../api/department'

// 移除模拟数据引入
// import { mockEmployees, mockDepartments } from '../../../mock/mockData'

const { confirm } = Modal

const Employee = () => {
    const [loading, setLoading] = useState(false)
    const [dataSource, setDataSource] = useState([])
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0
    })
    const [visible, setVisible] = useState(false)
    const [currentEmployee, setCurrentEmployee] = useState(null)
    const [viewVisible, setViewVisible] = useState(false)
    const [viewEmployee, setViewEmployee] = useState(null)
    const [departments, setDepartments] = useState([])
    const [searchKeyword, setSearchKeyword] = useState('')

    useEffect(() => {
        fetchEmployees()
        fetchDepartments()
    }, [pagination.current, pagination.pageSize, searchKeyword])
    
    // 获取部门列表
    const fetchDepartments = async () => {
        try {
            const response = await getDepartments();
            setDepartments(response.data || []);
        } catch (error) {
            console.error('获取部门列表失败:', error);
            message.error('获取部门列表失败');
        }
    };

    // 获取员工数据
    const fetchEmployees = async () => {
        setLoading(true);
        try {
            const response = await listEmployees({
                page: pagination.current,
                pageSize: pagination.pageSize,
                keyword: searchKeyword,
            });
            
            setDataSource(response.data || []);
            setPagination({
                ...pagination,
                total: response.total || 0
            });
        } catch (error) {
            console.error('获取员工列表失败:', error);
            message.error('获取员工列表失败');
        } finally {
            setLoading(false);
        }
    };

    // 处理表格变化
    const handleTableChange = (pagination) => {
        setPagination(pagination)
    }

    // 处理搜索
    const handleSearch = (value) => {
        setSearchKeyword(value)
    }

    // 添加员工
    const handleAdd = () => {
        setCurrentEmployee(null)
        setVisible(true)
    }

    // 编辑员工
    const handleEdit = async (record) => {
        try {
            setLoading(true);
            const response = await getEmployee(record.id);
            setCurrentEmployee(response);
            setVisible(true);
        } catch (error) {
            console.error('获取员工详情失败:', error);
            message.error('获取员工详情失败');
        } finally {
            setLoading(false);
        }
    };

    // 查看员工详情
    const handleView = async (record) => {
        try {
            setLoading(true);
            const response = await getEmployee(record.id);
            setViewEmployee(response);
            setViewVisible(true);
        } catch (error) {
            console.error('获取员工详情失败:', error);
            message.error('获取员工详情失败');
        } finally {
            setLoading(false);
        }
    };

    // 删除员工
    const handleDelete = (id) => {
        confirm({
            title: '确认删除',
            icon: <ExclamationCircleOutlined />,
            content: '确定要删除这名员工吗？此操作不可恢复。',
            onOk: async () => {
                try {
                    setLoading(true);
                    await deleteEmployee(id);
                    message.success('删除成功');
                    fetchEmployees();
                } catch (error) {
                    console.error('删除员工失败:', error);
                    message.error('删除员工失败');
                } finally {
                    setLoading(false);
                }
            }
        });
    };

    // 表单提交
    const handleFormSubmit = async (values) => {
        try {
            setLoading(true);
            if (currentEmployee) {
                // 编辑员工
                await updateEmployee(currentEmployee.id, values);
                message.success('编辑成功');
            } else {
                // 添加员工
                await createEmployee(values);
                message.success('添加成功');
            }
            // 关闭模态框
            setVisible(false);
            // 重新获取列表数据
            fetchEmployees();
        } catch (error) {
            console.error('保存员工失败:', error);
            message.error('保存员工失败');
        } finally {
            setLoading(false);
        }
    };

    // 表格列定义
    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            key: 'id',
            width: 80
        },
        {
            title: '姓名',
            dataIndex: 'name',
            key: 'name',
            render: (text, record) => (
                <a onClick={() => handleView(record)}>{text}</a>
            )
        },
        {
            title: '性别',
            dataIndex: 'gender',
            key: 'gender',
            width: 80
        },
        {
            title: '年龄',
            dataIndex: 'age',
            key: 'age',
            width: 80
        },
        {
            title: '部门',
            dataIndex: 'department_id',
            key: 'department_id',
            render: (departmentId) => {
                const dept = departments.find(d => d.id === departmentId);
                return dept ? dept.name : '-';
            }
        },
        {
            title: '职位',
            dataIndex: 'position',
            key: 'position'
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: (text) => {
                let color = text === '在职' ? 'green' : 'volcano'
                return <Tag color={color}>{text}</Tag>
            }
        },
        {
            title: '入职日期',
            dataIndex: 'entryDate',
            key: 'entryDate'
        },
        {
            title: '操作',
            key: 'action',
            width: 180,
            render: (_, record) => (
                <Space size="middle">
                    <Button 
                        type="text" 
                        icon={<EditOutlined />} 
                        onClick={() => handleEdit(record)}
                    >
                        编辑
                    </Button>
                    <Button 
                        type="text" 
                        danger 
                        icon={<DeleteOutlined />} 
                        onClick={() => handleDelete(record.id)}
                    >
                        删除
                    </Button>
                </Space>
            )
        }
    ]

    return (
        <div className="employee-container">
            <Card title="员工管理" extra={
                <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
                    添加员工
                </Button>
            }>
                <DataTable 
                    columns={columns}
                    dataSource={dataSource}
                    loading={loading}
                    rowKey="id"
                    pagination={pagination}
                    onChange={handleTableChange}
                    onSearch={handleSearch}
                    onRefresh={fetchEmployees}
                    searchPlaceholder="搜索员工姓名/部门/职位"
                />
            </Card>

            {/* 员工表单模态框 */}
            <Modal
                title={currentEmployee ? '编辑员工' : '添加员工'}
                open={visible}
                onCancel={() => setVisible(false)}
                footer={null}
                width={700}
            >
                <Form
                    initialValues={currentEmployee}
                    onFinish={handleFormSubmit}
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 20 }}
                >
                    <AntForm.Item
                        name="name"
                        label="姓名"
                        rules={[{ required: true, message: '请输入姓名' }]}
                    >
                        <input placeholder="请输入姓名" />
                    </AntForm.Item>
                    <AntForm.Item
                        name="gender"
                        label="性别"
                        rules={[{ required: true, message: '请选择性别' }]}
                    >
                        <select>
                            <option value="男">男</option>
                            <option value="女">女</option>
                        </select>
                    </AntForm.Item>
                    <AntForm.Item
                        name="age"
                        label="年龄"
                        rules={[{ required: true, message: '请输入年龄' }]}
                    >
                        <input type="number" placeholder="请输入年龄" />
                    </AntForm.Item>
                    <AntForm.Item
                        name="phone"
                        label="手机号"
                        rules={[{ required: true, message: '请输入手机号' }]}
                    >
                        <input placeholder="请输入手机号" />
                    </AntForm.Item>
                    <AntForm.Item
                        name="email"
                        label="邮箱"
                        rules={[{ required: true, message: '请输入邮箱' }]}
                    >
                        <input placeholder="请输入邮箱" />
                    </AntForm.Item>
                    <AntForm.Item
                        name="departmentId"
                        label="部门"
                        rules={[{ required: true, message: '请选择部门' }]}
                    >
                        <Select placeholder="请选择部门">
                            {departments.map(dept => (
                                <Select.Option key={dept.id} value={dept.id}>
                                    {dept.name}
                                </Select.Option>
                            ))}
                        </Select>
                    </AntForm.Item>
                    <AntForm.Item
                        name="position"
                        label="职位"
                        rules={[{ required: true, message: '请输入职位' }]}
                    >
                        <input placeholder="请输入职位" />
                    </AntForm.Item>
                    <AntForm.Item
                        name="status"
                        label="状态"
                        rules={[{ required: true, message: '请选择状态' }]}
                    >
                        <select>
                            <option value="在职">在职</option>
                            <option value="离职">离职</option>
                            <option value="试用期">试用期</option>
                        </select>
                    </AntForm.Item>
                    <AntForm.Item
                        name="entryDate"
                        label="入职日期"
                        rules={[{ required: true, message: '请选择入职日期' }]}
                    >
                        <input type="date" />
                    </AntForm.Item>
                    <AntForm.Item
                        name="address"
                        label="地址"
                    >
                        <input placeholder="请输入地址" />
                    </AntForm.Item>
                    <AntForm.Item
                        name="education"
                        label="学历"
                    >
                        <select>
                            <option value="高中">高中</option>
                            <option value="专科">专科</option>
                            <option value="本科">本科</option>
                            <option value="硕士">硕士</option>
                            <option value="博士">博士</option>
                        </select>
                    </AntForm.Item>
                    <AntForm.Item
                        name="salary"
                        label="薪资"
                    >
                        <input type="number" placeholder="请输入薪资" />
                    </AntForm.Item>
                </Form>
            </Modal>

            {/* 员工详情模态框 */}
            <Modal
                title="员工详情"
                open={viewVisible}
                onCancel={() => setViewVisible(false)}
                footer={null}
                width={700}
            >
                {viewEmployee && (
                    <div className="employee-detail">
                        <Row gutter={[16, 16]}>
                            <Col span={6} style={{ textAlign: 'center' }}>
                                <Avatar size={100} icon={<UserOutlined />} />
                                <h3 style={{ marginTop: 16 }}>{viewEmployee.name}</h3>
                                <p>{viewEmployee.position}</p>
                            </Col>
                            <Col span={18}>
                                <Tabs defaultActiveKey="1">
                                    <Tabs.TabPane tab="基本信息" key="1">
                                        <Descriptions bordered column={2}>
                                            <Descriptions.Item label="ID">{viewEmployee.id}</Descriptions.Item>
                                            <Descriptions.Item label="姓名">{viewEmployee.name}</Descriptions.Item>
                                            <Descriptions.Item label="性别">{viewEmployee.gender}</Descriptions.Item>
                                            <Descriptions.Item label="年龄">{viewEmployee.age}</Descriptions.Item>
                                            <Descriptions.Item label="手机号">{viewEmployee.phone}</Descriptions.Item>
                                            <Descriptions.Item label="邮箱">{viewEmployee.email}</Descriptions.Item>
                                            <Descriptions.Item label="部门">
                                                {departments.find(d => d.id === viewEmployee.departmentId)?.name || '-'}
                                            </Descriptions.Item>
                                            <Descriptions.Item label="职位">{viewEmployee.position}</Descriptions.Item>
                                            <Descriptions.Item label="状态">
                                                <Tag color={viewEmployee.status === '在职' ? 'green' : 'volcano'}>
                                                    {viewEmployee.status}
                                                </Tag>
                                            </Descriptions.Item>
                                            <Descriptions.Item label="入职日期">{viewEmployee.entryDate}</Descriptions.Item>
                                            <Descriptions.Item label="地址" span={2}>{viewEmployee.address}</Descriptions.Item>
                                        </Descriptions>
                                    </Tabs.TabPane>
                                    <Tabs.TabPane tab="其他信息" key="2">
                                        <Descriptions bordered column={2}>
                                            <Descriptions.Item label="学历">{viewEmployee.education}</Descriptions.Item>
                                            <Descriptions.Item label="薪资">{viewEmployee.salary}</Descriptions.Item>
                                        </Descriptions>
                                    </Tabs.TabPane>
                                </Tabs>
                            </Col>
                        </Row>
                    </div>
                )}
            </Modal>
        </div>
    )
}

export default Employee